import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/memory.dart';

class TimelineItem extends StatelessWidget {
  final Memory memory;
  final bool isLast;

  const TimelineItem({
    super.key,
    required this.memory,
    this.isLast = false,
  });

  @override
  Widget build(BuildContext context) {
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧时间线 - 参考HTML设计
          SizedBox(
            width: 50,
            child: Column(
              children: [
                // 时间锚点 - 圆形带边框，类似HTML的设计
                Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border.all(
                      color: Colors.pink.shade300,
                      width: 2,
                    ),
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Text(
                      DateFormat('M/d').format(memory.date),
                      style: TextStyle(
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                        color: Colors.pink.shade500,
                      ),
                    ),
                  ),
                ),
                // 连接线
                if (!isLast)
                  Expanded(
                    child: Container(
                      width: 2,
                      color: Colors.pink.shade200,
                    ),
                  ),
              ],
            ),
          ),
          
          const SizedBox(width: 16),
          
          // 右侧内容卡片 - 参考HTML的卡片设计
          Expanded(
            child: GestureDetector(
              onTap: () => _showMemoryDetail(context),
              child: Container(
                margin: const EdgeInsets.only(bottom: 32),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 顶部图片或文本预览区域 - 参考HTML设计
                    Container(
                      width: double.infinity,
                      height: 128, // 对应HTML的h-32
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(12),
                          topRight: Radius.circular(12),
                        ),
                        gradient: memory.hasImages 
                            ? null 
                            : _getGradientColor(memory.content),
                      ),
                      child: memory.hasImages
                          ? _buildImagePreview()
                          : _buildTextPreview(memory.content),
                    ),
                    
                    // 底部内容区域 - 参考HTML的p-4设计
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 标题
                          Text(
                            memory.title,
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.black87,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          
                          const SizedBox(height: 4),
                          
                          // 描述文字
                          Text(
                            memory.description ?? _getContentPreview(memory.content),
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey.shade600,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          
                          const SizedBox(height: 12),
                          
                          // 底部信息栏 - 参考HTML的设计
                          Row(
                            children: [
                              Text(
                                '发布人: ${memory.author}',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey.shade400,
                                ),
                              ),
                              const Spacer(),
                              if (memory.mood != null)
                                Text(
                                  '心情: ${memory.mood!.emoji}',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey.shade400,
                                  ),
                                ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建图片预览 - 参考HTML设计
  Widget _buildImagePreview() {
    return Stack(
      children: [
        // 主图片
        Container(
          width: double.infinity,
          height: double.infinity,
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(12),
              topRight: Radius.circular(12),
            ),
            image: DecorationImage(
              image: NetworkImage(_getImageUrl(memory.title)),
              fit: BoxFit.cover,
            ),
          ),
        ),
        // 多图片数量标识 - 参考HTML的+3设计
        if (memory.imageCount > 1)
          Positioned(
            top: 8,
            right: 8,
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 4,
              ),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.5),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                '+${memory.imageCount - 1}',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
      ],
    );
  }

  // 根据内容获取对应的图片URL
  String _getImageUrl(String title) {
    final imageMap = {
      '海边的日落': 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
      '第一次约会': 'https://images.unsplash.com/photo-1554118811-1e0d58224f24?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
      '今天的心情日记': 'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
      '一起做晚餐': 'https://images.unsplash.com/photo-1565299624946-b28f40a0ca4b?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
      '看电影的夜晚': 'https://images.unsplash.com/photo-1489185078527-623fcdc6a0f8?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
      '书店里的时光': 'https://images.unsplash.com/photo-1481627834876-b7833e8f5570?ixlib=rb-4.0.3&w=600&h=400&fit=crop',
    };
    
    return imageMap[title] ?? 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&w=600&h=400&fit=crop';
  }

  // 获取渐变背景色 - 参考HTML的渐变设计
  Gradient _getGradientColor(String content) {
    final gradients = [
      const LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [Color(0xFFF3E8FF), Color(0xFFFCE7F3)], // 紫粉渐变
      ),
      const LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [Color(0xFFEFF6FF), Color(0xFFE0E7FF)], // 蓝色渐变
      ),
      const LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [Color(0xFFF0FDF4), Color(0xFFDCFCE7)], // 绿色渐变
      ),
      const LinearGradient(
        begin: Alignment.topLeft,
        end: Alignment.bottomRight,
        colors: [Color(0xFFFFF7ED), Color(0xFFFFEDD5)], // 橙色渐变
      ),
    ];
    
    final index = content.length % gradients.length;
    return gradients[index];
  }

  // 构建纯文本预览 - 参考HTML的渐变背景设计
  Widget _buildTextPreview(String content) {
    final icon = _getContentIcon(memory.title);
    final previewText = _getContentPreview(content);
    
    return Container(
      decoration: BoxDecoration(
        gradient: _getGradientColor(content),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(12),
          topRight: Radius.circular(12),
        ),
      ),
      child: Center(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 图标
              Text(
                icon,
                style: const TextStyle(fontSize: 32),
              ),
              const SizedBox(height: 8),
              // 标题
              Text(
                memory.title,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.shade700,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 4),
              // 预览文字
              Text(
                previewText,
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey.shade600,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 根据标题获取对应图标
  String _getContentIcon(String title) {
    if (title.contains('诗')) return '📝';
    if (title.contains('思考') || title.contains('感悟')) return '💭';
    if (title.contains('心情') || title.contains('日记')) return '📖';
    if (title.contains('感谢')) return '🙏';
    return '💌';
  }

  // 获取内容预览文字
  String _getContentPreview(String content) {
    final lines = content.split('\n').where((line) => line.trim().isNotEmpty).toList();
    if (lines.isEmpty) return '';
    
    final firstLine = lines.first.trim();
    if (firstLine.length > 20) {
      return '${firstLine.substring(0, 20)}...';
    }
    return firstLine;
  }

  void _showMemoryDetail(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => MemoryDetailScreen(memory: memory),
      ),
    );
  }
}

class MemoryDetailScreen extends StatelessWidget {
  final Memory memory;

  const MemoryDetailScreen({super.key, required this.memory});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(memory.title),
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 信息栏
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade50,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Row(
                children: [
                  Text(
                    memory.author,
                    style: const TextStyle(fontSize: 20),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    DateFormat('yyyy年MM月dd日 HH:mm').format(memory.date),
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey.shade600,
                    ),
                  ),
                  const Spacer(),
                  if (memory.mood != null) ...[
                    Text(
                      memory.mood!.emoji,
                      style: const TextStyle(fontSize: 20),
                    ),
                    const SizedBox(width: 4),
                    Text(
                      memory.mood!.description,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade600,
                      ),
                    ),
                  ],
                ],
              ),
            ),
            
            const SizedBox(height: 20),
            
            // 图片画廊
            if (memory.hasImages) ...[
              SizedBox(
                height: 200,
                child: PageView.builder(
                  itemCount: memory.imagePaths.length,
                  itemBuilder: (context, index) {
                    return Container(
                      margin: const EdgeInsets.symmetric(horizontal: 4),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        image: DecorationImage(
                          image: AssetImage(memory.imagePaths[index]),
                          fit: BoxFit.cover,
                        ),
                      ),
                    );
                  },
                ),
              ),
              const SizedBox(height: 20),
            ],
            
            // 完整内容
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: Colors.grey.shade200,
                  width: 1,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 内容类型标识
                  Row(
                    children: [
                      Icon(
                        memory.hasImages ? Icons.photo_library_outlined : Icons.article_outlined,
                        size: 18,
                        color: Colors.grey.shade600,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        memory.hasImages ? '图文内容' : '纯文本内容',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      Text(
                        '${memory.content.length} 字',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade500,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  // 分隔线
                  Container(
                    height: 1,
                    color: Colors.grey.shade100,
                  ),
                  const SizedBox(height: 16),
                  // 文本内容
                  SelectableText(
                    memory.content,
                    style: const TextStyle(
                      fontSize: 16,
                      height: 1.8,
                      color: Colors.black87,
                      letterSpacing: 0.3,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}